package controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Student;
import pojo.User;
import service.StudentService;
import util.Page;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    // 全查询
    @RequestMapping("/list/{currentPage}")
    public String list(Student student, @PathVariable("currentPage") Integer currentPage, Model model){
        //查询数据
        Page page=new Page();
        int totalCount = studentService.count(student);
        page.setTotalCount(totalCount);
        page.setCurrentPage(currentPage);
        page.setTotalPage();

        // 计算偏移量
        int offset = (currentPage - 1) * page.getPageSize();
        List<Student> students = studentService.findAll(student, offset, page.getPageSize());

        // 数据返回
        model.addAttribute("students", students);
        model.addAttribute("page", page);
        model.addAttribute("student", student);
        // 补全代码
        return "student/list";
    }
    @RequestMapping("/toadd")
    public String toAdd(){
        return "student/add";
    }
    @RequestMapping("/addSave")
    public String addSave(Student student, HttpSession session){
        User user = (User)session.getAttribute("user");
        student.setCreate_by(user.getName());
        int result=studentService.addStudent(student);
        if(result>0){
            return "redirect:/student/list/1";
        }else{
            return "student/add";
        }
        }

    @RequestMapping("/delete/{s_id}")
    public String deleteUserById(@PathVariable("s_id") Integer s_id,Student student,HttpSession session){
        User user = (User)session.getAttribute("user");
        student.setUpdate_by(user.getName());
        student.setS_id(s_id);
        int result=studentService.deleteStudentById(student);
        return result > 0 ? "redirect:/student/list/1" : "error";
    }
    @RequestMapping("/toUpdate/{s_id}")
    public String toUpdate(@PathVariable("s_id") Integer s_id, Model model){
        Student student=studentService.findStudentById(s_id);
        model.addAttribute("student", student);
        return "student/update";
    }
    @RequestMapping("/updateSave")
    public String updateSave(Student student,HttpSession session){
        User user = (User)session.getAttribute("user");
        student.setUpdate_by(user.getName());
        int result=studentService.updateStudent(student);
        if (result > 0) {
            return "redirect:/student/list/1";
        } else {
            return "student/update";
        }
    }
}
